package com.zhifei.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.zhifei.common.core.redis.RedisCache;
import com.zhifei.common.utils.DateUtils;
import com.zhifei.common.utils.DispatcherUtils;
import com.zhifei.common.utils.Result;
import com.zhifei.common.utils.StringUtils;
import com.zhifei.system.domain.DingUserArchivesEntity;
import com.zhifei.system.domain.DingUserEntity;
import com.zhifei.system.domain.EmployeeEntity;
import com.zhifei.system.domain.JdPositionEntity;
import com.zhifei.system.domain.vo.DingUserDetailVo;
import com.zhifei.system.service.*;
import com.zhifei.system.util.DingCallbackCrypto;
import kingdee.bos.webapi.client.K3CloudApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class DingServiceImpl implements DingService {

    @Autowired
    private DingUserService dingUserService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private JdService jdService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JdPositionService jdPositionService;
    @Autowired
    private DingUserArchivesService dingUserArchivesService;

    @Override
    public Map<String, String> callBack(String msg_signature, String timeStamp, String nonce, JSONObject json) {
        try {
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，此时OWNER_KEY为应用的APP_KEY。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的appkey（企业内部应用）或SUITE_KEY（三方应用）
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto("hIIk7gftOU0Ok1FVtW8G2Bbs1ZDkb7IekDppMOdcCPzD6GbWocD", "2dXlDGLOuoV0ET1OFCxnpRGDfEyX4Prz1JfEU2inXAg", "dinghn88apo12gvr7gdv");
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 3. 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            log.info("eventJson:"+eventJson);
            String eventType = eventJson.getString("EventType");

            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
                log.info("测试回调url的正确性");
            } else if ("user_add_org".equals(eventType)) {
                // 处理通讯录用户增加事件
                addUser(eventJson);
            } else if ("user_modify_org".equals(eventType)) {
//                // 处理通讯录用户更改事件
                modifyUser(eventJson);
            } else if ("hrm_user_record_change".equals(eventType)) {
                // 处理花名册用户更改事件
                modifyHrmUser(eventJson);
            } else if ("user_leave_org".equals(eventType)) {
                // 处理通讯录用户离职事件
                removeUser(eventJson);
            } else if ("org_dept_create".equals(eventType)) {
                // 处理通讯录企业部门创建事件
                addDept(eventJson);
            } else if ("org_dept_modify".equals(eventType)) {
                // 处理通讯录企业部门修改事件
                modifyDept(eventJson);
            } else if ("org_dept_remove".equals(eventType)) {
                // 处理通讯录企业部门删除事件
                removeDept(eventJson);
            } else if ("bpms_instance_change".equals(eventType)) {
                // 处理审批实例开始、结束事件（现在只有调岗，为了取调岗时间）
                updatePost(eventJson);
            } else {
                // 添加其他已注册的
                log.info("发生了：" + eventType + "事件");
            }

            // 5. 返回success的加密数据
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    public Result test() {
//        addUser("19938245737");
        listAllUser();
//        getDismissDate("015519436948774889");
        return Result.success();
    }

    public void updatePost(JSONObject eventJson){
        String type = eventJson.getString("type");
        String title = eventJson.getString("title");
        if(type.equals("finish") && title.contains("调岗")){
            try {
                String processInstanceId = eventJson.getString("processInstanceId");
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
                OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
                req.setProcessInstanceId(processInstanceId);
                OapiProcessinstanceGetResponse rsp = client.execute(req, this.getAccessToken());
                JSONObject processResJson = JSON.parseObject(rsp.getBody());
                JSONObject processInstanceJson = JSON.parseObject(processResJson.getString("process_instance"));
                if(processInstanceJson.getString("result").equals("agree") && processInstanceJson.getString("status").equals("COMPLETED")){
                    String userId = processInstanceJson.getString("originator_userid");
                    JSONArray formComponentValuesJsonArray = processInstanceJson.getJSONArray("form_component_values");
                    JSONObject formComponentValueJson = (JSONObject) formComponentValuesJsonArray.get(0);
                    String valueStr = formComponentValueJson.getString("value");
                    JSONArray formJsonArray = JSONArray.parseArray(valueStr);
                    String updatePostDate = null;
                    String deptId = null;
                    if(formJsonArray!=null && formJsonArray.size()>0) {
                        for (int i = 0; i < formJsonArray.size(); i++) {
                            JSONObject fieldDataJson = (JSONObject) formJsonArray.get(i);
                            String componentType = fieldDataJson.getString("componentType");
                            if(componentType.equals("DDDateField")){
                                updatePostDate = fieldDataJson.getString("value");
                            }
                            if(componentType.equals("DepartmentField")){
                                JSONArray extValueJsonArray = JSONArray.parseArray(fieldDataJson.getString("extValue"));
                                JSONObject extValueJson = (JSONObject) extValueJsonArray.get(0);
                                deptId = extValueJson.getString("id");
                            }
                        }
                    }
                    DingUserEntity dingUserEntity = dingUserService.lambdaQuery().eq(DingUserEntity::getUserId,userId).one();
                    if(dingUserEntity!=null){
                        if(!deptId.equals(dingUserEntity.getDeptId())){
                            Date leaveProjectDate = DateUtils.parseDate(updatePostDate);
                            DingUserArchivesEntity dingUserArchivesEntity = new DingUserArchivesEntity();
                            BeanUtils.copyProperties(dingUserEntity,dingUserArchivesEntity);
                            dingUserArchivesEntity.setMonth(DateUtils.getDateFirstDayOfMonth(leaveProjectDate));
                            dingUserArchivesEntity.setUserStatus(3);
                            dingUserArchivesEntity.setLeaveProjectDate(leaveProjectDate);
                            dingUserArchivesService.save(dingUserArchivesEntity);//如果部门发生改变则新增项目人员档案记录
                            employeeService.updatePost(dingUserEntity.getJobNumber(),updatePostDate);//如果部门发生改变则执行调岗
                        }
                    }
                    dingUserService.lambdaUpdate()
                            .set(DingUserEntity::getDeptId,deptId)
                            .eq(DingUserEntity::getUserId,userId)
                            .update();
                }
            } catch (ApiException e) {
            }
        }

    }

    public String getDismissDate(String userId){
        String dismissDate = null;
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/listdimission");
        OapiSmartworkHrmEmployeeListdimissionRequest req = new OapiSmartworkHrmEmployeeListdimissionRequest();
        req.setUseridList(userId);
        OapiSmartworkHrmEmployeeListdimissionResponse rsp = null;
        try {
            rsp = client.execute(req, getAccessToken());
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
        System.out.println(rsp.getBody());
        JSONObject userResJson = JSON.parseObject(rsp.getBody());
        JSONArray userListJson = userResJson.getJSONArray("result");
        if(userListJson!=null && userListJson.size()>0){
            JSONObject userJson = (JSONObject) userListJson.get(0);
            Long lastWorkDay = userJson.getLong("last_work_day");
            Date date = new Date(lastWorkDay);
            dismissDate = DateUtils.dateTime(date);
        }
        return dismissDate;
    }

    public void listAllUser(){
//        List<DingUserEntity> dingUserEntityList = dingUserService.lambdaQuery().isNull(DingUserEntity::getDeptId).list();
        List<DingUserEntity> dingUserEntityList = dingUserService.lambdaQuery().list();
        List<EmployeeEntity> employeeEntityList = employeeService.listDistinctEmployee();
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
//        String accessToken = getAccessToken();
        for(DingUserEntity dingUserEntity : dingUserEntityList){
//            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
//            req.setUserid(dingUserEntity.getUserId());
//            req.setLanguage("zh_CN");
//            OapiV2UserGetResponse rsp = null;
//            try {
//                rsp = client.execute(req, accessToken);
//            } catch (ApiException e) {
//                throw new RuntimeException(e);
//            }
//            JSONObject userResJson = JSON.parseObject(rsp.getBody());
//            JSONObject userJson = JSON.parseObject(userResJson.getString("result"));
//            Integer deptId = null;
//            if(userJson==null){
//                deptId = 999;
//            }else{
//                JSONArray deptIdListJson = userJson.getJSONArray("dept_id_list");
//                if(deptIdListJson!=null && deptIdListJson.size()>0){
//                    deptId = (Integer) deptIdListJson.get(0);
//                }
//            }
            DingUserDetailVo dingUserDetailVo = getUserDetail(dingUserEntity.getUserId());
            dingUserService.lambdaUpdate().
                    set(DingUserEntity::getDeptId,dingUserDetailVo.getDepartmentId())
                    .set(DingUserEntity::getFullName,dingUserDetailVo.getUserName())
                    .set(DingUserEntity::getUserPost,dingUserDetailVo.getPositionName())
                    .set(DingUserEntity::getUserRank,dingUserDetailVo.getRankName())
                    .set(DingUserEntity::getMonthPay,dingUserDetailVo.getMonthPay())
                    .eq(DingUserEntity::getUserId,dingUserEntity.getUserId())
                    .update();
            for(EmployeeEntity employeeEntity : employeeEntityList){
                if(StringUtils.isNotEmpty(dingUserEntity.getJobNumber()) && dingUserEntity.getJobNumber().equals(employeeEntity.getJobNum())){
                    dingUserService.lambdaUpdate()
                            .set(DingUserEntity::getMonthPay,employeeEntity.getMonthPay())
                            .set(DingUserEntity::getQuoteMonthPay,employeeEntity.getQuoteMonthPay())
                            .set(DingUserEntity::getProjectName,employeeEntity.getProjectName())
                            .set(DingUserEntity::getSocialSecurity,employeeEntity.getSocialSecurity())
                            .eq(DingUserEntity::getJobNumber,dingUserEntity.getJobNumber())
                            .update();
                }
            }

        }

    }

    public void addDept(JSONObject eventJson) throws Exception {
        try {
            List<String> deptIdList = JSON.parseArray(eventJson.getString("DeptId"), String.class);
            for(String deptIdStr : deptIdList){
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
                OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
                req.setDeptId(DispatcherUtils.parseLong(deptIdStr));
                req.setLanguage("zh_CN");
                OapiV2DepartmentGetResponse rsp = client.execute(req, this.getAccessToken());
                JSONObject deptResJson = JSON.parseObject(rsp.getBody());
                JSONObject deptJson = JSON.parseObject(deptResJson.getString("result"));
                String deptId = deptJson.getString("dept_id");//部门id
                String deptName = deptJson.getString("name");//部门名称
                String parentId = deptJson.getString("parent_id");//上级部门id
                K3CloudApiClient k3CloudApiClient = login();
                JSONObject k3CloudObj = new JSONObject();
                k3CloudObj.put("IsAutoSubmitAndAudit", "true");
                k3CloudObj.put("IsAutoAdjustField", "true");
                JSONObject deptK3CloudObj = new JSONObject();
                deptK3CloudObj.put("FCreateOrgId",FNumber("100"));
                deptK3CloudObj.put("FUseOrgId",FNumber("100"));
                deptK3CloudObj.put("FDeptProperty",FNumber("DP01_SYS"));
                deptK3CloudObj.put("FNumber",deptId);
                deptK3CloudObj.put("FName",deptName);
                deptK3CloudObj.put("FParentID",FNumber(parentId));
                k3CloudObj.put("Model",deptK3CloudObj);
                String params = JSONObject.toJSONString(k3CloudObj);
                String addDeptResult = k3CloudApiClient.save("BD_Department", params);
                JSONObject k3CloudResultJson = JSON.parseObject(addDeptResult);
                JSONObject allocateDeptObj = new JSONObject();
                allocateDeptObj.put("IsAutoAdjustField", "true");
                allocateDeptObj.put("IsAutoSubmitAndAudit", "true");
                allocateDeptObj.put("PkIds",JSON.parseObject(k3CloudResultJson.getString("Result")).getString("Id"));
                allocateDeptObj.put("TOrgIds","1,100169,100170,109555");
                k3CloudApiClient.excuteOperation("BD_Department","Allocate",JSONObject.toJSONString(allocateDeptObj));
            }
        } catch (ApiException e) {
        }
    }

    public void modifyDept(JSONObject eventJson) throws Exception {
        try {
            List<String> deptIdList = JSON.parseArray(eventJson.getString("DeptId"), String.class);
            for(String deptIdStr : deptIdList){
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
                OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
                req.setDeptId(DispatcherUtils.parseLong(deptIdStr));
                req.setLanguage("zh_CN");
                OapiV2DepartmentGetResponse rsp = client.execute(req, this.getAccessToken());
                JSONObject deptResJson = JSON.parseObject(rsp.getBody());
                JSONObject deptJson = JSON.parseObject(deptResJson.getString("result"));
                String deptId = deptJson.getString("dept_id");//部门id
                String deptName = deptJson.getString("name");//部门名称
                String parentId = deptJson.getString("parent_id");//上级部门id
                K3CloudApiClient k3CloudApiClient = login();
                JSONObject viewObj = new JSONObject();
                viewObj.put("Number",deptId);
                String viewResult = k3CloudApiClient.view("BD_Department",JSONObject.toJSONString(viewObj));
                JSONObject viewJson = JSON.parseObject(JSON.parseObject(JSON.parseObject(viewResult).getString("Result")).getString("Result"));
                JSONObject k3CloudObj = new JSONObject();
                k3CloudObj.put("IsAutoAdjustField", "true");
                JSONObject deptK3CloudObj = new JSONObject();
                JSONObject deptProperty = JSON.parseObject(viewJson.getString("DeptProperty"));
                deptK3CloudObj.put("FDEPTID",viewJson.getString("Id"));
                deptK3CloudObj.put("FCreateOrgId",FNumber("100"));
                deptK3CloudObj.put("FUseOrgId",FNumber("100"));
                deptK3CloudObj.put("FDeptProperty",FNumber(deptProperty.getString("FNumber")));
                deptK3CloudObj.put("FNumber",deptId);
                deptK3CloudObj.put("FName",deptName);
                deptK3CloudObj.put("FParentID",FNumber(parentId));
                k3CloudObj.put("Model",deptK3CloudObj);
                String params = JSONObject.toJSONString(k3CloudObj);
                String addDeptResult = k3CloudApiClient.save("BD_Department", params);
                log.info("******************");
                log.info("addDeptResult:"+addDeptResult);
            }
        } catch (ApiException e) {
        }
    }

    public void removeDept(JSONObject eventJson) throws Exception {
        try {
            List<String> deptIdList = JSON.parseArray(eventJson.getString("DeptId"), String.class);
            for(String deptIdStr : deptIdList){
                K3CloudApiClient k3CloudApiClient = login();
                JSONObject k3CloudObj = new JSONObject();
                k3CloudObj.put("Numbers",new String[]{deptIdStr});
                k3CloudApiClient.excuteOperation("BD_Department","Forbid",JSONObject.toJSONString(k3CloudObj));
            }
        } catch (ApiException e) {
        }
    }

    public String getAccessToken(){
        String accessToken = redisCache.getCacheObject("ding_access_token");
        if(StringUtils.isEmpty(accessToken)){
            try {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                OapiGettokenRequest request = new OapiGettokenRequest();
                request.setAppkey("dinghn88apo12gvr7gdv");
                request.setAppsecret("eMrgiD4sbzumJzHsB1M8JpVGGWHXGiRLf44dHyd-qQV9kvUNrMNwT6KNfCtR2HNQ");
                request.setHttpMethod("GET");
                OapiGettokenResponse response = client.execute(request);
                JSONObject eventJson = JSON.parseObject(response.getBody());
                accessToken = eventJson.getString("access_token");
                redisCache.setCacheObject("ding_access_token", accessToken, 7200, TimeUnit.SECONDS);
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
        }
        return accessToken;
    }

    public K3CloudApiClient login(){
        K3CloudApiClient client = new K3CloudApiClient("https://zhifei.ik3cloud.com/k3cloud/");
        Boolean login;
        try {
            login = client.login("1372529010512232448","administrator","zhifei123456@",2052);
            // 判断是否登录 如果登录成功 返回 对象 否则报异常
            if (login) {
                return client;
            }
        } catch (Exception e) {
        }
        return client;
    }

    public static JSONObject FNumber(String fNumber){
        JSONObject transData = new JSONObject();
        transData.put("FNumber",fNumber);
        return transData;
    }

    public void addUser(JSONObject eventJson){
        try {
            String accessToken = this.getAccessToken();
            List<String> userIdList = JSON.parseArray(eventJson.getString("UserId"), String.class);
            for(String userIdStr : userIdList){
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
                OapiV2UserGetRequest req = new OapiV2UserGetRequest();
                req.setUserid(userIdStr);
                req.setLanguage("zh_CN");
                OapiV2UserGetResponse rsp = client.execute(req, accessToken);
                JSONObject userResJson = JSON.parseObject(rsp.getBody());
                JSONObject userJson = JSON.parseObject(userResJson.getString("result"));
                String jobNumber = userJson.getString("job_number");//用户工号
                String userName = userJson.getString("name");//用户名称
                String userMobile = userJson.getString("mobile");//用户手机号
                Integer deptId = null;
                JSONArray deptIdListJson = userJson.getJSONArray("dept_id_list");
                if(deptIdListJson!=null && deptIdListJson.size()>0){
                    deptId = (Integer) deptIdListJson.get(0);
                }
                addK3CloudUser(jobNumber,userName,userMobile);
                DingUserDetailVo dingUserDetailVo = getUserDetail(userIdStr);
                dingUserService.add(userIdStr,DispatcherUtils.parseString(deptId),dingUserDetailVo);
                DingTalkClient departmentClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
                OapiV2DepartmentGetRequest departmentReq = new OapiV2DepartmentGetRequest();
                departmentReq.setDeptId(DispatcherUtils.parseLong(deptId));
                departmentReq.setLanguage("zh_CN");
                OapiV2DepartmentGetResponse departmentRsp = departmentClient.execute(departmentReq, accessToken);
                log.info(departmentRsp.getBody());
                if(departmentRsp.getResult().getParentId()!=null && departmentRsp.getResult().getParentId().equals(657191536L)){
                    addPlatformUser(dingUserDetailVo);
                }
                log.info("#############");
            }
        } catch (ApiException e) {
        }
    }

    /**
     * 新增金蝶用户
     * @param userId
     * @param userName
     * @param userMobile
     */
    public void addK3CloudUser(String userId,String userName,String userMobile){
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("IsAutoSubmitAndAudit", "true");
            k3CloudObj.put("IsAutoAdjustField", "true");
            JSONObject userK3CloudObj = new JSONObject();
            userK3CloudObj.put("FCreateOrgId",FNumber("100"));
            userK3CloudObj.put("FUseOrgId",FNumber("100"));
            userK3CloudObj.put("FName",userName);
            userK3CloudObj.put("FStaffNumber",userId);
            userK3CloudObj.put("FMobile",userMobile);
            k3CloudObj.put("Model",userK3CloudObj);
            String params = JSONObject.toJSONString(k3CloudObj);
            String addUserResult = k3CloudApiClient.save("BD_Empinfo", params);
            log.info("***********************");
            log.info("addUserResult:"+addUserResult);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 替换薪人薪事用户入职接口
     */
    public void addPlatformUser(DingUserDetailVo dingUserDetailVo){
        String k3cloudPositionId = null;
        String k3cloudRankId = null;

        JdPositionEntity jdPositionEntity = jdPositionService.getByPositionName(dingUserDetailVo.getPositionName());
        if(jdPositionEntity!=null && StringUtils.isNotEmpty(jdPositionEntity.getK3cloudId())){
            k3cloudPositionId = jdPositionEntity.getK3cloudId();
        }
        String rankName = dingUserDetailVo.getRankName();
        if(StringUtils.isNotEmpty(rankName)){
            if(rankName.equals("初级")){
                k3cloudRankId = "CJ";
            }else if(rankName.equals("初中级")){
                k3cloudRankId = "CZJ";
            }else if(rankName.equals("中级")){
                k3cloudRankId = "ZJ";
            }else if(rankName.equals("中高级")){
                k3cloudRankId = "ZGJ";
            }else if(rankName.equals("高级")){
                k3cloudRankId = "GJ";
            }
        }
        //新增数据到金蝶系统物料
        jdService.addK3cloudMaterial(dingUserDetailVo.getJobNumber(),dingUserDetailVo.getUserName(),dingUserDetailVo.getUserMobile(),k3cloudPositionId,k3cloudRankId,dingUserDetailVo.getMonthPay(),dingUserDetailVo.getQuoteMonthPay());
        //新增数据到数据中台employee表中
        addEmployee(dingUserDetailVo.getJobNumber(),dingUserDetailVo.getUserName(),dingUserDetailVo.getPositionName(),rankName, DateUtils.parseDate(dingUserDetailVo.getEntryDate()),new BigDecimal(dingUserDetailVo.getMonthPay()),dingUserDetailVo.getRecruitHr());
    }

    public DingUserDetailVo getUserDetail(String userId){
        DingUserDetailVo dingUserDetailVo = new DingUserDetailVo();
        try {
            String accessToken = getAccessToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/v2/list");
            OapiSmartworkHrmEmployeeV2ListRequest req = new OapiSmartworkHrmEmployeeV2ListRequest();
            req.setUseridList(userId);
            req.setFieldFilterList("sys00-name,sys00-mobile,sys00-jobNumber,e67fb83c-69d7-4d43-94aa-69b6f3687cb5,sys00-confirmJoinTime," +
                    "sys00-deptIds,sys00-dept,sys00-position,sys01-positionLevel,29aa8a58-cf95-4ef7-a7f6-9a3fc1f8a7c6,58e4811f-27da-4e87-a19b-d4ffdad851f0");
            req.setAgentid(1758722446L);
            OapiSmartworkHrmEmployeeV2ListResponse rsp = client.execute(req, accessToken);
            log.info(rsp.getBody());
            JSONObject userResJson = JSON.parseObject(rsp.getBody());
            JSONArray userJsonArray = userResJson.getJSONArray("result");
            JSONObject userJson = (JSONObject) userJsonArray.get(0);
            String userName = null;//员工姓名
            String userMobile = null;//员工手机号
            String jobNumber = null;//员工工号
            String recruitHr = null;//招聘专员
            String entryDate = null;//入职时间
            String departmentId = null;//部门id
            String departmentName = null;//部门名称
            String positionName = null;//岗位
            String rankName = null;//职级
            String monthPay =null;//月薪
            String quoteMonthPay = null;//报价月薪
            JSONArray fieldDataListJson= userJson.getJSONArray("field_data_list");
            if(fieldDataListJson!=null && fieldDataListJson.size()>0) {
                for (int i = 0; i < fieldDataListJson.size(); i++) {
                    JSONObject fieldDataJson = (JSONObject) fieldDataListJson.get(i);
                    String fieldCode = fieldDataJson.getString("field_code");
                    JSONArray fieldValueListJson = fieldDataJson.getJSONArray("field_value_list");
                    if(fieldValueListJson!=null && fieldValueListJson.size()>0){
                        JSONObject fieldValueJson = (JSONObject) fieldValueListJson.get(0);
                        switch (fieldCode){
                            case "sys00-name":
                                userName = fieldValueJson.getString("value");
                                break;
                            case "sys00-mobile":
                                userMobile = fieldValueJson.getString("value").replaceAll("\\+86-","");
                                break;
                            case "sys00-jobNumber":
                                jobNumber = fieldValueJson.getString("value");
                                break;
                            case "e67fb83c-69d7-4d43-94aa-69b6f3687cb5":
                                recruitHr = fieldValueJson.getString("value");
                                break;
                            case "sys00-confirmJoinTime":
                                entryDate = fieldValueJson.getString("value");
                                break;
                            case "sys00-deptIds":
                                departmentId = fieldValueJson.getString("value");
                                break;
                            case "sys00-dept":
                                departmentName = fieldValueJson.getString("value");
                                break;
                            case "sys00-position":
                                positionName = fieldValueJson.getString("value");
                                break;
                            case "sys01-positionLevel":
                                rankName = fieldValueJson.getString("value");
                                break;
                            case "29aa8a58-cf95-4ef7-a7f6-9a3fc1f8a7c6":
                                monthPay = fieldValueJson.getString("value");
                                break;
                            case "58e4811f-27da-4e87-a19b-d4ffdad851f0":
                                quoteMonthPay = fieldValueJson.getString("value");
                                break;
                        }
                    }
                }
            }
            dingUserDetailVo.setUserName(userName);
            dingUserDetailVo.setUserMobile(userMobile);
            dingUserDetailVo.setJobNumber(jobNumber);
            dingUserDetailVo.setRecruitHr(recruitHr);
            dingUserDetailVo.setEntryDate(entryDate);
            dingUserDetailVo.setDepartmentId(departmentId);
            dingUserDetailVo.setDepartmentName(departmentName);
            dingUserDetailVo.setPositionName(positionName);
            dingUserDetailVo.setRankName(rankName);
            dingUserDetailVo.setMonthPay(monthPay);
            dingUserDetailVo.setQuoteMonthPay(quoteMonthPay);
        } catch (Exception e) {
        }
        return dingUserDetailVo;
    }

    public void addEmployee(String jobNum, String fullName, String userPost, String userRank, Date admissionDate, BigDecimal monthPay, String recruitHr){
        EmployeeEntity employeeEntity = new EmployeeEntity();
        employeeEntity.setProjectType(2);//默认为2，如果纷享销客中订单明细匹配到会修改为1
        employeeEntity.setJobNum(jobNum);
        employeeEntity.setFullName(fullName);
        employeeEntity.setUserPost(userPost);
        employeeEntity.setUserRank(userRank);
        employeeEntity.setAdmissionDate(admissionDate);
        employeeEntity.setMonthPay(monthPay);
        employeeEntity.setRecruitHr(recruitHr);
        employeeEntity.setEmployeeStatus(1);
        employeeService.save(employeeEntity);
    }

//    public void addXrxsEmployee(String jobNum,String deptId,String name,String mobile,String entryDate,String recruitHr){
//        XrxsEmployeeEntity xrxsEmployeeEntity = new XrxsEmployeeEntity();
//        xrxsEmployeeEntity.setName(name);
//        xrxsEmployeeEntity.setMobile(mobile);
//        xrxsEmployeeEntity.setEntryDate(entryDate);
//        xrxsEmployeeEntity.setRecruitHr(recruitHr);
//        xrxsEmployeeEntity.setEmployeeNo(jobNum);
//        xrxsEmployeeEntity.setDeptId(deptId);
//        xrxsEmployeeMapper.insert(xrxsEmployeeEntity);
//    }

    public void modifyUser(JSONObject eventJson) {
        try {
            String accessToken = this.getAccessToken();
            List<String> userIdList = JSON.parseArray(eventJson.getString("UserId"), String.class);
            for(String userIdStr : userIdList){
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
                OapiV2UserGetRequest req = new OapiV2UserGetRequest();
                req.setUserid(userIdStr);
                req.setLanguage("zh_CN");
                OapiV2UserGetResponse rsp = client.execute(req, accessToken);
                JSONObject userResJson = JSON.parseObject(rsp.getBody());
                JSONObject userJson = JSON.parseObject(userResJson.getString("result"));
                String userId = userJson.getString("job_number");//用户id
                String userName = userJson.getString("name");//用户名称
                String userMobile = userJson.getString("mobile");//用户手机号
                modifyK3CloudUser(userId,userName,userMobile);
                Integer deptId = null;
                JSONArray deptIdListJson = userJson.getJSONArray("dept_id_list");
                if(deptIdListJson!=null && deptIdListJson.size()>0){
                    deptId = (Integer) deptIdListJson.get(0);
                }
                DingTalkClient departmentClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
                OapiV2DepartmentGetRequest departmentReq = new OapiV2DepartmentGetRequest();
                departmentReq.setDeptId(DispatcherUtils.parseLong(deptId));
                departmentReq.setLanguage("zh_CN");
                OapiV2DepartmentGetResponse departmentRsp = departmentClient.execute(departmentReq, accessToken);
                log.info(departmentRsp.getBody());
                DingUserDetailVo dingUserDetailVo = getUserDetail(userIdStr);
                if(departmentRsp.getResult().getParentId()!=null && departmentRsp.getResult().getParentId().equals(657191536L)){
                    modifyPlatformUser(userIdStr,dingUserDetailVo,DispatcherUtils.parseString(deptId));
                }
                dingUserService.update(userIdStr,DispatcherUtils.parseString(deptId),dingUserDetailVo);
            }
        } catch (ApiException e) {
        }
    }

    public void modifyHrmUser(JSONObject eventJson) {
        try {
            String accessToken = this.getAccessToken();
            String userIdStr = eventJson.getString("staffId");
            if(StringUtils.isEmpty(userIdStr)){
                return;
            }
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userIdStr);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, accessToken);
            JSONObject userResJson = JSON.parseObject(rsp.getBody());
            if(userResJson.getString("errcode").equals("60121")){
                return;
            }
            JSONObject userJson = JSON.parseObject(userResJson.getString("result"));
            String userId = userJson.getString("job_number");//用户id
            String userName = userJson.getString("name");//用户名称
            String userMobile = userJson.getString("mobile");//用户手机号
            modifyK3CloudUser(userId,userName,userMobile);
            Integer deptId = null;
            JSONArray deptIdListJson = userJson.getJSONArray("dept_id_list");
            if(deptIdListJson!=null && deptIdListJson.size()>0){
                deptId = (Integer) deptIdListJson.get(0);
            }
            DingTalkClient departmentClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest departmentReq = new OapiV2DepartmentGetRequest();
            departmentReq.setDeptId(DispatcherUtils.parseLong(deptId));
            departmentReq.setLanguage("zh_CN");
            OapiV2DepartmentGetResponse departmentRsp = departmentClient.execute(departmentReq, accessToken);
            log.info(departmentRsp.getBody());
            DingUserDetailVo dingUserDetailVo = getUserDetail(userIdStr);
            if(departmentRsp.getResult().getParentId()!=null && departmentRsp.getResult().getParentId().equals(657191536L)){
                modifyPlatformUser(userIdStr,dingUserDetailVo,DispatcherUtils.parseString(deptId));
            }
            dingUserService.update(userIdStr,DispatcherUtils.parseString(deptId),dingUserDetailVo);
        } catch (ApiException e) {
        }
    }

    public void modifyPlatformUser(String userId,DingUserDetailVo dingUserDetailVo,String deptId){
        employeeService.updateEmployee(dingUserDetailVo.getJobNumber(),dingUserDetailVo.getPositionName(),dingUserDetailVo.getRankName(),new BigDecimal(dingUserDetailVo.getMonthPay()),dingUserDetailVo.getRecruitHr());
    }

    /**
     * 修改金蝶用户
     * @param userId
     * @param userName
     * @param userMobile
     */
    public void modifyK3CloudUser(String userId,String userName,String userMobile){
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject viewObj = new JSONObject();
            viewObj.put("Number",userId);
            String viewResult = k3CloudApiClient.view("BD_Empinfo", JSONObject.toJSONString(viewObj));
            JSONObject viewJson = JSON.parseObject(JSON.parseObject(JSON.parseObject(viewResult).getString("Result")).getString("Result"));
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("IsAutoSubmitAndAudit", "true");
            k3CloudObj.put("IsAutoAdjustField", "true");
            JSONObject userK3CloudObj = new JSONObject();
            userK3CloudObj.put("FID",viewJson.getString("Id"));
            userK3CloudObj.put("FCreateOrgId",FNumber("100"));
            userK3CloudObj.put("FUseOrgId",FNumber("100"));
            userK3CloudObj.put("FName",userName);
            userK3CloudObj.put("FStaffNumber",userId);
            userK3CloudObj.put("FMobile",userMobile);
            k3CloudObj.put("Model",userK3CloudObj);
            String params = JSONObject.toJSONString(k3CloudObj);
            JSONObject unAuditObj = new JSONObject();
            unAuditObj.put("Numbers",new String[]{userId});
            k3CloudApiClient.unAudit("BD_Empinfo", JSONObject.toJSONString(unAuditObj));
            String modifyUserResult = k3CloudApiClient.save("BD_Empinfo", params);
            log.info("***********************");
            log.info("modifyUserResult:"+modifyUserResult);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void removeUser(JSONObject eventJson){
        List<String> userIdList = JSON.parseArray(eventJson.getString("UserId"), String.class);
        for(String userIdStr : userIdList){
            String jobNumber = dingUserService.get(userIdStr).getJobNumber();
            removeK3CloudUser(jobNumber);
            removePlatformUser(userIdStr,jobNumber);
        }
    }

    public void removePlatformUser(String userId,String jobNum){
        try {
            String dismissDate = getDismissDate(userId);
            //employee表修改该员工状态为离职
            employeeService.dismissEmployee(jobNum,dismissDate);
            //ding_user表修改该员工状态为离职
            dingUserService.dismissUser(jobNum,dismissDate);
        }catch (Exception e){
        }

    }

    /**
     * 禁用金蝶用户
     * @param userId
     */
    public void removeK3CloudUser(String userId){
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("Numbers",new String[]{userId});
            String removeUserResult = k3CloudApiClient.excuteOperation("BD_Empinfo","Forbid", JSONObject.toJSONString(k3CloudObj));
            log.info("***********************");
            log.info("removeUserResult:"+removeUserResult);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
